import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { setToken , getToken , getQueryString } from '@/utils/auth';
//import loginUrl from '@/service/loginUrl.js'
import { getMenuByUserId } from '@/service/swagger/MenuController'
NProgress.configure({ showSpinner: false })// NProgress Configuration
import { Notification,MessageBox } from 'element-ui'
//// permission judge function
//function hasPermission(roles, permissionRoles) {
//if (roles.indexOf('admin') >= 0) return true // admin permission passed directly
//if (!permissionRoles) return true
//return roles.some(role => permissionRoles.indexOf(role) >= 0)
//}

const whiteList = ['/login', '/authredirect']// no redirect whitelist

//修改后台返回得数据结构
const  bianli = function(obj) {
	if (obj.children) {
		obj.children.forEach(el => {
			el.name = el.text
			el.hidden = el.attributes.status ? false : true
			el.path = el.attributes.url
			el.meta = {
				title:el.text,
				iconfont:el.attributes.icon
			}
			bianli(el)
			return obj
		})
		return obj.children
	}
}

//取本后台返回得菜单path array
const getLocalRoute = function(array){
	var arr = []
	 array.forEach(el=>{
		 arr.push(el.path)
		 if(el.children){
			 arr.push(...getLocalRoute(el.children))
		 }
	 })
	 console.log(arr)
	 return arr
}


let hasAddRouter ;
let routesPath ;
router.beforeEach((to, from, next) => {
	
	if(window.intelVal){
		clearInterval(window.intelVal)
	}
	 
	if(!hasAddRouter){
		// 用户未登录
		store.dispatch('setUserInfo').then(ret => { // 拉取user_info
      if(ret){
				// window.location.href = 'http://10.21.237.35:9999'
				//获取菜单树
				getMenuByUserId(JSON.parse(ret).userId).then(ret=>{
					if(ret&&ret.code == 0){
							console.log(router.options.routes,'本地路由')//本地路由对象
							console.log(ret.data.children,'后台返回')//后台返回路由树
							let obj = {
								children:ret.data.children
							}
							let menuList =	bianli(obj)
							console.log(menuList,'数据结构改变')
							store.dispatch('GenerateRoutes',menuList)
							
							routesPath = getLocalRoute(ret.data.children)
					}
				})
			}
			next();
			
			router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
			hasAddRouter = true ;

		});
	}else{
		// console.log(routesPath.indexOf(to.path),'ssssssssssssssssssssssss')
		// if(routesPath.indexOf(to.path) == -1){
		// 	Notification.warning({ title: '警告', message: '你没有权限进入该页面' , duration : 2000 })
		// }else{
	  // 	next()
		// }
		next();
	}
	
//NProgress.start() // start progress bar
//if(to.path === '/login'){
//	
//}
//if (getToken()) { // determine if there has token
//  /* has token*/
//  if (to.path === '/login') {
//    next({ path: '/' })
//    NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
//  } else {
//    if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
//      store.dispatch('GetUserInfo').then(ret => { // 拉取user_info
//        const roles = ret.roles // note: roles must be a array! such as: ['editor','develop']
//        store.dispatch('GenerateRoutes', { roles }).then(() => { // 根据roles权限生成可访问的路由表
//          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
//          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
//        })
//      }).catch((err) => {
//        store.dispatch('FedLogOut').then(() => {
//          Message.error(err || 'Verification failed, please login again')
//          next({ path: '/' })
//        })
//      })
//    } else {
//      // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
//      if (hasPermission(store.getters.roles, to.meta.roles)) {
//        next()//
//      } else {
//        next({ path: '/401', replace: true, query: { noGoBack: true }})
//      }
//      // 可删 ↑
//    }
//  }
//} else {
//  /* has no token*/
//  if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
//    next()
//  } else {
//  	window.location.href = loginUrl;
//  	return ;
////    next('/login') // 否则全部重定向到登录页
////    NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
//  }
//}

})

router.afterEach(() => {
  // NProgress.done() // finish progress bar
})
